package com.ymatou.iapi.messageroute.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import com.ymatou.iapi.messageroute.parameter.BizTypeEnum;
import com.ymatou.iapi.messageroute.parameter.MessageBody;
import com.ymatou.iapi.messageroute.parameter.MongoMessageRouteMsgTaskConfig;
import com.ymatou.iapi.messageroute.parameter.MsgItem;
import com.ymatou.iapi.messageroute.parameter.MsgTask;
import com.ymatou.messageroute.api.parameter.GetScenarioMessageBean;
import com.ymatou.messageroute.api.parameter.MessageTaskBean;
import com.ymatou.messageroute.api.parameter.MessageToolTaskBean;
import com.ymatou.messageroute.api.service.GetScenarioMessageCall;
import com.ymt.core.tool.FormatUtil;
import com.ymt.core.tool.Logger;
import com.ymttest.common.enums.BusinessTypeEnum;
import com.ymttest.database.mongo.config.SchemaField;
import com.ymttest.utils.DataUtil;
import com.ymttest.utils.YMTDateUtil;

public class SendTradingMsgService {

	public static void verfiyWithNet(BizTypeEnum bizTypeEnum, int userId,
			int orderId) {

		MessageTaskBean expectMessageTask = getScenarioMessageFromNet(orderId,
				userId, BusinessTypeEnum.forValue(bizTypeEnum.getCode()));

		MsgTask actualMsgTask = getMsgTaskByOrderId(bizTypeEnum,
				String.valueOf(orderId));

		if (null == expectMessageTask) {
			Logger.verifyIsNull(actualMsgTask, "校验该场景下发送消息为空");
		}

		else {

			if (null == actualMsgTask) {
				Logger.verifyNotNull(actualMsgTask, "校验该场景下发送消息不为空");
				return;
			}

			Logger.verifyEquals(Long.valueOf(expectMessageTask.getUserId()),
					actualMsgTask.getUserId(), "验证userId");

			verifyNet(expectMessageTask, actualMsgTask);
		}

	}

	public static void verify() {

	}

	public static void verifyNet(MessageTaskBean expectMessageTask,
			MsgTask actualMsgTask) {

		List<MessageToolTaskBean> messageToolTaskBeanList = expectMessageTask
				.getMessageToolTasks();

		List<MsgItem> msgItemList = actualMsgTask.getMsgItems();

		Logger.verifyEquals(messageToolTaskBeanList.size(), msgItemList.size(),
				"验证新老消息路由发需要发送消息的渠道数一致");

		for (int i = 0; i < messageToolTaskBeanList.size(); i++) {

			MessageToolTaskBean expectMessage = messageToolTaskBeanList.get(i);

			int j = expectMessage.getMessageTool() == 4 ? 3 : expectMessage
					.getMessageTool();

			boolean isExist = msgItemList.stream().anyMatch(
					m -> m.getMsgTp() == j);

			DataUtil.verify(true, isExist, "验证期望的发送消息渠道=[" + j
					+ "]在新的消息路由系统中是否存在");

			if (isExist) {

				MsgItem actualMessage = (MsgItem) msgItemList.stream()
						.filter(m -> m.getMsgTp() == j)
						.collect(Collectors.toList()).get(0);

				verfiyMessageBody(expectMessage, actualMessage);
			}

		}
	}
	private static void verfiyMessageBody(MessageToolTaskBean expectMessage,
			MsgItem actualMessage) {
		try {

			DataUtil.verify(expectMessage.getMessageTool() == 4
					? 3
					: expectMessage.getMessageTool(), actualMessage.getMsgTp(),
					"验证新老消息路由发需要发送消息的渠道编号");

			MessageBody actualMessageBody = (MessageBody) FormatUtil
					.GSONToObject(actualMessage.getMsgBody(), MessageBody.class);

			HashMap<String, String> expectMessageContent = new HashMap<String, String>();

			HashMap<String, String> actualMessageContent = new HashMap<String, String>();

			switch (expectMessage.getMessageTool()) {

			//手机短信
				case 1 :
					Logger.comment("校验手机短信渠道消息体");
					DataUtil.verify(expectMessage.getMessageBody(),
							actualMessageBody.getMsgContent(),
							"校验短信 msgContent");
					DataUtil.verify(expectMessage.getUserMessageAdress(),
							actualMessageBody.getMsgReceiver(),
							"校验短信 msgReceiver");
					DataUtil.verify(expectMessage.getSuccess(),
							actualMessage.isSuccess(), "校验短信 发送结果");

					Logger.verifyEquals(true, YMTDateUtil.diffMinute(
							actualMessage.getDueTime(), new Date()) < 1,
							"校验预计执行时间");
					Logger.verifyEquals(true, YMTDateUtil.diffMinute(
							actualMessage.getExecTime(), new Date()) < 1,
							"校验实际执行时间");
					break;

				//IM 消息
				case 2 :

					expectMessageContent = (HashMap<String, String>) FormatUtil
							.GSONToObject(expectMessage.getMessageBody(),
									HashMap.class);
					actualMessageContent = (HashMap<String, String>) FormatUtil
							.GSONToObject(actualMessageBody.getMsgContent(),
									HashMap.class);

					Logger.comment("校验IM渠道消息体");

					DataUtil.verify(expectMessageContent.get("IsShangouOrder"),
							actualMessageContent.get("IsShangouOrder"),
							"校验IM IsShangouOrder");
					DataUtil.verify(expectMessageContent.get("Title"),
							actualMessageContent.get("Title"), "校验IM Title");

					DataUtil.verify(expectMessageContent.get("Content"),
							actualMessageContent.get("Content"), "校验IM Content");

					DataUtil.verify(expectMessageContent.get("OrderId"),
							actualMessageContent.get("OrderId"), "校验IM OrderId");

					DataUtil.verify(expectMessageContent.get("FreeShopping"),
							actualMessageContent.get("FreeShopping"),
							"校验IM FreeShopping");

					DataUtil.verify(expectMessageContent.get("FreeTax"),
							actualMessageContent.get("FreeTax"), "校验IM FreeTax");

					DataUtil.verify(expectMessage.getImNotifyUserId(),
							actualMessageBody.getMsgReceiver(),
							"校验IM msgReceiver");
					DataUtil.verify(expectMessage.getSuccess(),
							actualMessage.isSuccess(), "校验IM渠道 发送结果");

					Logger.verifyEquals(true, YMTDateUtil.diffMinute(
							actualMessage.getDueTime(), new Date()) < 1,
							"校验预计执行时间");
					Logger.verifyEquals(true, YMTDateUtil.diffMinute(
							actualMessage.getExecTime(), new Date()) < 1,
							"校验实际执行时间");
					break;
				//微信消息
				case 4 :

					expectMessageContent = (HashMap<String, String>) FormatUtil
							.GSONToObject(expectMessage.getMessageBody(),
									HashMap.class);

					actualMessageContent = (HashMap<String, String>) FormatUtil
							.GSONToObject(actualMessageBody.getMsgContent(),
									HashMap.class);

					Logger.comment("校验微信渠道消息体");

					DataUtil.verify(expectMessageContent.get("first"),
							actualMessageContent.get("first"), "校验微信 first");

					DataUtil.verify(expectMessageContent.get("keyword1"),
							actualMessageContent.get("keyword1"),
							"校验微信 keyword1");

					DataUtil.verify(expectMessageContent.get("keyword2"),
							actualMessageContent.get("keyword2"),
							"校验微信 keyword2");

					DataUtil.verify(expectMessageContent.get("remark"),
							actualMessageContent.get("remark"), "校验微信 remark");

					DataUtil.verify(expectMessage.getWeixinTemplateId(),
							actualMessageBody.getMsgReceiver(),
							"校验微信 msgReceiver");

					DataUtil.verify(expectMessage.getUrl(),
							actualMessageBody.getMsgTitle(), "校验微信 msgTitle");
					DataUtil.verify(expectMessage.getSuccess(),
							actualMessage.isSuccess(), "校验微信 渠道 发送结果");

					Logger.verifyEquals(true, YMTDateUtil.diffMinute(
							actualMessage.getDueTime(), new Date()) < 1,
							"校验预计执行时间");
					Logger.verifyEquals(true, YMTDateUtil.diffMinute(
							actualMessage.getExecTime(), new Date()) < 1,
							"校验实际执行时间");
					break;

			}
		} catch (Exception e) {
			// TODO: handle exception

			e.printStackTrace();
		}

	}
	/**
	 * 根据订单号，BizTypeEnum 业务类型查询mongo 消息
	 * @param userId 用户id
	 * @param orderId 订单号	
	 * @return MsgTask
	 */
	public static MsgTask getMsgTaskByOrderId(BizTypeEnum bizTypeEnum,
			String orderId) {

		MsgTask msgTask = null;

		try {

			MongoTemplate template = new MongoMessageRouteMsgTaskConfig()
					.mongoTemplate();

			String queryCondition = bizTypeEnum.getMessageCode() + orderId;

			;
			Logger.comment(String.format("mongo 查询条件为: \"_id\":\"%s\"",
					queryCondition));

			Query query = Query.query(Criteria.where("_id").in(queryCondition));

			msgTask = template
					.find(query,
							MsgTask.class,
							SchemaField.MSGTASK
									+ new SimpleDateFormat("yyyyMM")
											.format(new Date())).get(0);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return msgTask;
	}
	/**
	 * 根据订单号，用户id，日期，查询老.net消息路由消息
	 * @param orderId 订单号
	 * @param userId 用户id
	 * @return GetScenarioMessageCall
	 */
	public static MessageTaskBean getScenarioMessageFromNet(int orderId,
			int userId, BusinessTypeEnum type) {

		MessageTaskBean messageTask = new MessageTaskBean();
		GetScenarioMessageBean getScenarioMessageBean = new GetScenarioMessageBean();

		GetScenarioMessageCall getScenarioMessageCall = new GetScenarioMessageCall();

		try {

			getScenarioMessageBean.setBusinessType(type);
			getScenarioMessageBean.setOrderId(orderId);
			getScenarioMessageBean.setUserId(userId);
			getScenarioMessageBean.setMessageDueTime(YMTDateUtil
					.getSysTime("yyyy-MM-dd"));
			getScenarioMessageCall.setData(getScenarioMessageBean);
			getScenarioMessageCall.callService();

			Thread.sleep(5000);

			getScenarioMessageCall.callService();

			messageTask = getScenarioMessageCall.getMessageTask();

		} catch (Exception e) {
			Logger.fail(e);
		}
		return messageTask;
	}

	public static void main(String args[]) {

	}

}
